from fastapi_user_auth.admin import AuthAdminSite
from sqlalchemy import String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from fastapi import FastAPI
from fastapi_amis_admin.admin.settings import Settings
from fastapi_amis_admin.admin.site import AdminSite
from fastapi_amis_admin.admin import admin
# from sqlmodel import SQLModel
# from models.table_defs import Category

class Base(DeclarativeBase):
    pass
#
# # 创建SQLAlchemy 2.0模型,详细请参考: https://docs.sqlalchemy.org/en/20/orm/quickstart.html
class Category(Base):
    __tablename__ = "category"

    id: Mapped[int] = mapped_column(primary_key=True, nullable=False)
    name: Mapped[str] = mapped_column(String(100), unique=True, index=True, nullable=False)
    description: Mapped[str] = mapped_column(String(255), default="")
#


app = FastAPI()

# 创建AdminSite实例
# site = AdminSite(settings=Settings(database_url_async='sqlite+aiosqlite:///amisadmin.db'))
site = AuthAdminSite(settings=Settings(database_url_async='sqlite+aiosqlite:///amisadmin2.db?check_same_thread=False'))
auth = site.auth

# 注册ModelAdmin
@site.register_admin
class CategoryAdmin(admin.ModelAdmin):
    page_schema = '分类管理'
    # 配置管理模型
    model = Category
    # 配置管理字段

site.mount_app(app)


# 创建初始化数据库表
@app.on_event("startup")
async def startup():
    # await site.db.async_run_sync(SQLModel.metadata.create_all, is_session=False)
    await site.db.async_run_sync(Base.metadata.create_all, is_session=False)

    await auth.create_role_user("admin")
    # 创建默认超级管理员,用户名: root,密码: root, 请及时修改密码!!!
    await auth.create_role_user("root")
    # 运行site的startup方法,加载casbin策略等
    await site.router.startup()
    # 添加一条默认的casbin规则
    if not auth.enforcer.enforce("u:admin", site.unique_id, "page", "page"):
        await auth.enforcer.add_policy("u:admin", site.unique_id, "page", "page", "allow")

if __name__ == '__main__':
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=18000)